package cn.ryanpenn.es.ms.city.service.impl;

import cn.ryanpenn.es.ms.city.model.City;
import cn.ryanpenn.es.ms.city.service.CityService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * CityServiceImpl
 *
 * @author pennryan
 */
@Service
public class CityServiceImpl implements CityService {

    private List<City> cityList = new ArrayList<>();

    @Override
    public List<City> getCityList(boolean reload) throws IOException {

        if (reload) {
            load();
        }

        return cityList;
    }

    @PostConstruct
    private void load() throws IOException {
        Resource resource = new ClassPathResource("citykey.txt");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            String line;
            String[] pairDate;
            while ((line = reader.readLine()) != null) {
                pairDate = line.split(",");
                if (pairDate.length == 2) {
                    cityList.add(new City(pairDate[1], pairDate[0]));
                } else {
                    // TODO: 此处的逻辑仅用于开发调试
                    // 碰到空行就停止,避免文件过大,耗费太多时间
                    break;
                }
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
}
